using System;
using System.IO;
using System.Net;

namespace gtalk
{
    /// <summary>
    /// Summary description for Authentication.
    /// </summary>
    public class Authentication
    {
        private string loginUrl = "https://www.google.com/accounts/ServiceLoginBoxAuth";
        private string gmailUrl = "https://mail.google.com/mail/";

        public Authentication()
        {
        }

        public void Login()
        {
            System.Net.WebRequest webRequest = System.Net.HttpWebRequest.Create(
                loginUrl);
            string postDataStr = string.Format("Email={0}&Passwd={1}&continue={2}",
                Config.Email, Config.Password, this.gmailUrl);
            byte[] postData = System.Text.Encoding.Default.GetBytes(postDataStr);
            webRequest.Method = "Post";
            webRequest.ContentLength = postData.Length;
            webRequest.ContentType = "application/x-www-form-urlencoded";
            System.IO.Stream stream = webRequest.GetRequestStream();
            stream.Write(postData, 0, postData.Length);
            stream.Close();

            WebResponse webResponse = webRequest.GetResponse();
            Stream getStream = webResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(getStream, System.Text.Encoding.Default);
            string getStr = "";
            string tmpStr = "";
            while ((tmpStr = streamReader.ReadLine()) != null)
                getStr += tmpStr + "\n";
            streamReader.Close();
            getStream.Close();
            this.AddLog(getStr);

            HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)webResponse;
            foreach (System.Net.Cookie cookie in httpWebResponse.Cookies)
                this.AddLog(cookie.Name + " : " + cookie.Value);
        }

        public string GetToken()
        {
            System.Net.WebRequest webRequest = System.Net.HttpWebRequest.Create(
                Config.ClientAuthUrl);
            string postDataStr = string.Format("Email={0}&Passwd={1}&PersistentCookie=false&source=googletalk",
                Config.Email, Config.Password);
            byte[] postData = System.Text.Encoding.Default.GetBytes(postDataStr);
            webRequest.Method = "Post";
            webRequest.ContentLength = postData.Length;
            webRequest.ContentType = "application/x-www-form-urlencoded";
            
            //			System.IO.Stream stream;
            System.IO.Stream stream = webRequest.GetRequestStream();
            stream.Write(postData, 0, postData.Length);
            stream.Close();
            this.AddLog("Send >> " + postDataStr);
            WebResponse webResponse = webRequest.GetResponse();
            Stream getStream = webResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(getStream, System.Text.Encoding.Default);
            string getStr = "";
            string tmpStr = "";
            while ((tmpStr = streamReader.ReadLine()) != null)
                getStr += tmpStr + "\n";
            streamReader.Close();
            getStream.Close();
            this.AddLog("Recrived >> " + getStr);

            string[] tmpStrs = getStr.Split('\n');
            if (tmpStrs.Length < 2)
                return string.Empty;
            if (tmpStrs[0].Split('=').Length < 2 || tmpStrs[1].Split('=').Length < 2)
                return string.Empty;
            string sid = tmpStrs[0].Split('=')[1];
            string lsid = tmpStrs[1].Split('=')[1];

            webRequest = HttpWebRequest.Create(Config.IssueAuthTokenUrl);
            postDataStr = string.Format("SID={0}&LSID={1}&service=mail&Session=true&skipvpage=true", sid, lsid);
            postData = System.Text.Encoding.Default.GetBytes(postDataStr);
            webRequest.Method = "Post";
            webRequest.ContentLength = postData.Length;
            webRequest.ContentType = "application/x-www-form-urlencoded";

            stream = webRequest.GetRequestStream();
            stream.Write(postData, 0, postData.Length);
            stream.Close();
            this.AddLog("Send >> " + postDataStr);
            webResponse = webRequest.GetResponse();
            getStream = webResponse.GetResponseStream();
            streamReader = new StreamReader(getStream, System.Text.Encoding.Default);
            getStr = "";
            while ((tmpStr = streamReader.ReadLine()) != null)
                getStr += tmpStr + "\n";
            streamReader.Close();
            getStream.Close();
            this.AddLog("Recrived >> " + getStr);

            return getStr;
        }

        public void AddLog(string logStr)
        {
            Console.WriteLine(logStr);
        }
    }
}
